﻿using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint;
using PeoplePickerPlus.Helpers;

namespace PeoplePickerPlus.CONTROLTEMPLATES.PeoplePickerPlus
{
    public partial class ControlInjector : UserControl
    {
        private const string ClientResourceVersion = "1.7.16";

        private static string _excludedPages = null;
        private const string DefaultExcludedPages = "\"cstwrkflip.aspx\",\"/NintexWorkflow/\"";
        private static bool? _allowShowSecurityGroupMembers;

        public ControlInjector()
        {
            UseAlphaButtons = true;
        }

        protected bool UseAlphaButtons
        {
            get;
            set;
        }

        protected string GetExcludedPages()
        {
            if (_excludedPages == null)
            {
                _excludedPages = DefaultExcludedPages;

                string[] pages = Configuration.GetAppSetting(Configuration.PeoplePickerExcludedPagesSetting, "").Split(';');
                
                for (int i = 0; i < pages.Length; i++)
                {
                    string page = pages[i].Trim().TrimStart('"').TrimEnd('"');
                    if (!string.IsNullOrEmpty(page))
                    {
                        _excludedPages += string.Format(",\"{0}\"", pages[i].Trim().TrimStart('"').TrimEnd('"'));
                    }
                }
            }
            return _excludedPages;
        }

        protected bool ShowSecurityGroupMembers
        {
            get
            {
                return CanBrowseUserInfo && AllowShowSecurityGroupMembers;
            }
        }

        private bool AllowShowSecurityGroupMembers
        {
            get
            {
                if (!_allowShowSecurityGroupMembers.HasValue)
                {
                    _allowShowSecurityGroupMembers = string.Equals(Configuration.GetAppSetting(Configuration.PeoplePickerShowSecurityGroupMembers, "true"), "true", StringComparison.OrdinalIgnoreCase);
                }
                return _allowShowSecurityGroupMembers.Value;
            }
        }

        protected bool CanBrowseUserInfo
        {
            get
            {
                try
                {
                    return SPContext.Current.Web.DoesUserHavePermissions(SPBasePermissions.BrowseUserInfo);
                }
                catch
                {
                    return false;
                }
            }
        }

        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            
            CssRegistration.Register(string.Format("{0}/_layouts/PeoplePickerPlus/PeoplePickerPlus{2}.css?v={1}",
                SPContext.Current.Site.RootWeb.ServerRelativeUrl.TrimEnd('/'),
                ClientResourceVersion,
                Minified ? ".min" : null 
                ));

            RegisterJavascript(Page.ClientScript, string.Format("jquery.SPPeoplePickerPlus{1}.js?v={0}",
                        ClientResourceVersion,
                        Minified ? ".min" : null));


            InitializeAddons();
        }

        protected virtual void InitializeAddons()
        {
            if (UseAlphaButtons)
            {
                CssRegistration.Register(string.Format("{0}/_layouts/PeoplePickerPlus/Addons/AlphaButtons.css?v={1}",
                SPContext.Current.Site.RootWeb.ServerRelativeUrl.TrimEnd('/'),
                ClientResourceVersion));

                RegisterJavascript(Page.ClientScript, string.Format("Addons/jquery.AlphaButtons{1}.js?v={0}",
                        ClientResourceVersion,
                        Minified ? ".min" : null));
            }
        }

        private static void RegisterJavascript(ClientScriptManager sm, string relativePath)
        {
            if (!sm.IsClientScriptBlockRegistered(relativePath))
            {
                sm.RegisterClientScriptBlock(typeof(ControlInjector), relativePath, string.Format("<script src=\"{0}/_layouts/PeoplePickerPlus/{1}\" type=\"text/javascript\"></script>",
                    SPContext.Current.Site.RootWeb.ServerRelativeUrl.TrimEnd('/'), relativePath));
            }
        }

        private bool Minified
        {
            get
            {
#if DEBUG
                return false;
#else
                return true;
#endif
            }
        }
    }
}
